// 停车场基本处理函数模块

const db = require('../mysql/index')
// 引入公共的方法
const commonFunction = require('../common/common')


// 新增停车场
exports.parkingAdd = async (req, res) => {
    const data = req.body
    // 格式转换
    data.enable == 'true' ? data.enable = 1 : data.enable = 0
    const { parkingName, area, address, type, carsNumber, enable, coord } = data
    // 查询停车场是否存在
    const selcerSql = 'select id, parkingName, area, address, type, carsNumber, enable, coord FROM parking WHERE parkingName = ?'
    db.query(selcerSql, parkingName, (cerr, cresult) => {
        if (cerr) return res.cc(cerr)
        if (cresult.length !== 0) return res.cc('该停车场已存在')
        // 插入的数据
        const dataArr = [parkingName, area, address, type, carsNumber, enable, coord]
        const addSql = 'INSERT INTO parking(parkingName, area, address, type, carsNumber, enable, coord) VALUES(?,?,?,?,?,?,?) '
        db.query(addSql, dataArr, (addErr, addResult) => {
            if (addErr) return res.cc(addErr);
            if (addResult.affectedRows !== 1) return res.cc('新增停车场失败')
            return res.send({
                code: 200,
                message: '新增停车场成功'
            })
        })
    })
}

// 删除停车场
exports.parkingDelete = (req, res) => {
    const id = req.query.id
    const checkSql = 'select id, parkingName, area, address, type, carsNumber, enable, coord FROM parking WHERE id = ?'
    db.query(checkSql, id, (err, result) => {
        if (err) return res.cc(err)
        // 查询成功
        if (result.length === 1) {
            const sql = 'DELETE FROM parking WHERE id = ?'
            db.query(sql, id, (queryErr, queryResult) => {
                if (queryErr) return res.cc(queryErr)
                if (queryResult.affectedRows !== 1) return res.cc('删除失败')
                return res.send({
                    code: 200,
                    message: '删除成功'
                })
            })
        } else return res.cc('没有该停车场')
    })

}

// 获取停车场列表
exports.parkingList = (req, res) => {
    let { pageNumber, pageSize, parkingName, enable, type, address, area } = req.body
    // 可能需要提交的字段
    let paramsObj = {
        parkingName,
        address,
        enable,
        type,
        area
    }
    // 每页大小和偏移量
    pageSize = Number(pageSize)
    const offset = (Number(pageNumber) - 1) * pageSize
    // 有无其余参数的标志
    let flag = false
    let paramsSql = 'SELECT * FROM parking where '
    // 对sql进行参数处理
    const paramsArr = []
    const paramsValue = []
    for (const key in paramsObj) {
        const obj = {}
        if (paramsObj[key] !== undefined && paramsObj[key] !== '') {
            // 对布尔值和字符串的数字进行处理
            if (paramsObj[key] == 1 || paramsObj[key] == 0) { paramsObj[key] = Number(paramsObj[key]) }
            if (paramsObj[key] == 'true') { paramsObj[key] = 1 }
            if (paramsObj[key] == 'false') { paramsObj[key] = 0 }
            obj[key] = paramsObj[key]
            paramsArr.push(obj)
            flag = true
        }
    }
    paramsArr.forEach((item, index) => {
        if (index === paramsArr.length - 1) {
            if (item.parkingName || item.address) {
                paramsSql += Object.keys(item) + ' like "%' + item[Object.keys(item)] + '%"'
            } else {
                paramsSql += Object.keys(item) + '= ?'
                paramsValue.push(item[Object.keys(item)])
            }
        } else {
            // 对停车场名称和地址进行模糊查询
            if (item.parkingName || item.address) {
                paramsSql += Object.keys(item) + ' like "%' + item[Object.keys(item)] + '%" and '
            } else {
                paramsSql += Object.keys(item) + ' = ? and '
                paramsValue.push(item[Object.keys(item)])
            }
        }
    });
    if (!flag) {
        // 无参其余参数
        const sql = 'SELECT * FROM parking'
        db.query(sql, (err, result) => {
            if (err) return res.cc(err)
            if (result.length === 0) return res.send({ code: 201, message: '未查询到停车场' })
            // 将省市区代码转换为中文
            let counter = 0;
            result.forEach(async item => {
                const areaArr = item.area.split(',')
                const areaName = await commonFunction.getCityName(areaArr)
                item.area = areaName[0]
                item.enable === 1 ? item.enable = true : item.enable = false
                counter++;
                if (counter === result.length) {
                    let data = result.slice(offset, offset + pageSize)
                    return res.send({
                        code: 200,
                        message: '获取停车场列表成功',
                        data,
                        total: result.length
                    })
                }
            })
        })
    } else {
        // 有其余参数
        db.query(paramsSql, [...paramsValue], (err, result) => {
            if (err) return res.cc(err)
            if (result.length === 0) return res.send({ code: 201, message: '未查询到停车场' })
            // 将省市区代码转换为中文
            let counter = 0;
            result.forEach(async item => {
                const areaArr = item.area.split(',')
                const areaName = await commonFunction.getCityName(areaArr)
                item.area = areaName[0]
                item.enable === 1 ? item.enable = true : item.enable = false
                counter++;
                if (counter === result.length) {
                    let data = result.slice(offset, offset + pageSize)
                    return res.send({
                        code: 200,
                        message: '获取停车场列表成功',
                        data,
                        total: result.length
                    })
                }
            })
        })
    }
}

// 获取指定停车场详情
exports.parkingDetail = (req, res) => {
    const id = req.query.id
    // 查询sql
    const sql = 'SELECT * FROM parking WHERE id = ?'
    // 获取省市区中文sql
    const getNameSql = 'SELECT province_name, city_name, area_name FROM province, city, area WHERE province_code = ? and city_code = ? and area_code = ?'
    // 查询停车场
    db.query(sql, id, (err, result) => {
        if (err) return res.cc(err)
        if (result.length !== 1) return res.cc('暂未查询到停车场')
        // 查询省市区中文
        const regionArr = result[0].area.split(',')
        db.query(getNameSql, regionArr, (err1, result1) => {
            if (err1) return res.cc(err1)
            if (result1.length !== 1) return false;
            let region = [result1[0].province_name, result1[0].city_name, result1[0].area_name.trim()].join(',')
            result[0].region = region
            const data = JSON.parse(JSON.stringify(result[0]))
            // 对禁启用字段处理
            data.enable === 1 ? data.enable = true : data.enable = false
            return res.send({
                code: 200,
                message: '获取停车场详情成功',
                data
            })
        })
    })
}

// 编辑停车场
exports.parkingEdit = (req, res) => {
    let { parkingName, area, address, type, carsNumber, enable, coord, id } = req.body
    enable == 'true' ? enable = 1 : enable = 0
    const sql = 'UPDATE parking SET parkingName=?, area=?, address=?, type=?, carsNumber=?, enable=?, coord=? WHERE id = ?'
    db.query(sql, [parkingName, area, address, type, carsNumber, enable, coord, id], (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc('修改失败')
        return res.send({
            code: 200,
            message: '修改停车场信息成功'
        })
    })
}

// 修好禁启用状态
exports.parkingEnable = (req, res) => {
    let { id, enable } = req.query
    enable === 'true' ? enable = 1 : enable = 0
    const sql = 'UPDATE parking set enable = ? WHERE id = ?'
    db.query(sql, [enable, id], (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc('修改状态失败')
        return res.send({
            code: 200,
            message: '修改状态成功'
        })
    })
}



// web端
// 停车场以及车的数量
exports.webParking = (req, res) => {
    const sql = 'SELECT parking.id, parkingName, coord, COUNT(parking_id) as carsNumber FROM parking, car WHERE parking.enable = 1 GROUP BY parking.id'
    db.query(sql, (err, result) => {
        if (err) return err
        if (result.length === 0) return res.send({code: 200, message: '停车场为空', data: []})
        const sql1 = 'SELECT parking.id, parkingName, coord, COUNT(parking_id) as carsNumber FROM parking, car WHERE parking.enable = 1 and car.enable = 1 and parking_id = parking.id GROUP BY parking.id'
        db.query(sql1, (err1, result1) => {
            if (err1) return res.cc(err1)
            for (let iterator of result) {
                var item = result1.find(ele => ele.id === iterator.id)
                if (item) {
                    iterator.carsNumber = item.carsNumber
                } else {
                    iterator.carsNumber = 0
                }
            }
            return res.send({
                code: 200,
                message: '获取停车场信息成功',
                data: result
            })
        })
    })
}